//
//  QMapLocationVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/18.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QMapLocationVC.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "QPlaceMapCell.h"
#import "QPerfectOrderInforMationVC.h"
@interface QMapLocationVC ()<MAMapViewDelegate, AMapLocationManagerDelegate,AMapSearchDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) MAPointAnnotation *pointAnnotation;
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIButton *centerBtn;

@end

@implementation QMapLocationVC{

    NSInteger _zoomLeve;//地图放大每数

    NSTimer *_timer;
    NSInteger _addIndex;
    UIImageView *_pointImageView;//中心图标
    NSMutableArray *_pointArr;//装中心图标移动的数据

    NSMutableArray *_dataArr;//列表数据
    UITableView *_tableView;
    UIView *_whiteView;//输入框的背景视图
    
    UIControl *_maskView;
}


- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    [_timer invalidate];
    _timer = nil;
    
}
- (void)dealloc{
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeFromSuperview];
    
    _mapView = nil;
    _locationManager = nil;
    _pointAnnotation = nil;
    _search = nil;
    
    CLog(@"地图销毁");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地图";
    _dataArr = [NSMutableArray array];
    _pointArr = [NSMutableArray array];

    [self setupForDismissKeyboard];
    [self createMap];//初始化地图和定位
    [self createTextField];//创建搜索
    [self createTableView];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

#pragma mark --- 初始化定位和地图
- (void)createMap{
    
    _zoomLeve = 15;
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];
   // [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    _pointAnnotation = [[MAPointAnnotation alloc]init];//**********mapviewmodel
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0,(kNavHeight+kStatusHeight),kScreenWidth,kScreenHeight-(kNavHeight+kStatusHeight))];//地图
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    [_mapView setZoomLevel:_zoomLeve];
    [_mapView setMapType:MAMapTypeStandard];
    [self.view addSubview:_mapView];
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
    _centerBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth-120)/2,(kScreenHeight-(kNavHeight+kStatusHeight))/2-70,120,70)];
    [_centerBtn setImage:[UIImage imageNamed:@"maphead_image"] forState:UIControlStateNormal];
    [_centerBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    _centerBtn.tag = 3;
    [self.mapView addSubview:_centerBtn];
    _pointImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 14, 15, 15)];
    _pointImageView.image = [UIImage imageNamed:@"mapbluepoint_image"];
    [_centerBtn addSubview:_pointImageView];
    
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(kScreenWidth-50, kScreenHeight-100-(kNavHeight+kStatusHeight), 40, 40);
    button1.tag = 1;
    [button1 setImage:[UIImage imageNamed:@"zoomOut_image"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:button1];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(kScreenWidth-50, button1.bottom, 40, 40);
    button2.tag = 2;
    [button2 setImage:[UIImage imageNamed:@"zooIn_image"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:button2];
    
    _maskView = [[UIControl alloc] init];
    _maskView.hidden = YES;
    _maskView.backgroundColor = [UIColor clearColor];
    [_mapView addSubview:_maskView];
    [_maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_mapView).insets(UIEdgeInsetsZero);
    }];
    
    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.alpha = 0.9;
    visualEffectView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenMask)];
    [visualEffectView addGestureRecognizer:tap];
    [_maskView addSubview:visualEffectView];
    [visualEffectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_mapView).insets(UIEdgeInsetsZero);
    }];
}


#pragma mark --- 隐藏maskview
- (void)hiddenMask{
    _maskView.alpha = 1;
    [UIView animateWithDuration:0.5 animations:^{
        _maskView.alpha = 0;
    }completion:^(BOOL finished) {
        _maskView.alpha = 1;
        _maskView.hidden = YES;
    }];
    [_textField resignFirstResponder];
}

#pragma mark --- 定时器
- (void)timerAction{
    _addIndex++;
    if(_addIndex%2 == 0){
        _pointImageView.image = [UIImage imageNamed:@"mapbluepoint_image"];
    }else{
        _pointImageView.image = [UIImage imageNamed:@"mapgreenpoint_image"];
    }
}

#pragma mark --- 创建textfiled
- (void)createTextField{
    UILabel *agreeLabel = [QViewUtility createLabelWithFrame:CGRectMake(_pointImageView.right+8, 12, 0, 0) font:Ksize16 textAlignment:NSTextAlignmentCenter textColor:[UIColor whiteColor] text:@"确定地址"];
    [agreeLabel sizeToFit];
    [_centerBtn addSubview:agreeLabel];
    
    _whiteView = [[UIView alloc] initWithFrame:CGRectMake(15, 20, kScreenWidth-30, 40)];
    _whiteView.backgroundColor = [UIColor whiteColor];
    _whiteView.layer.cornerRadius = 2;
    [_mapView addSubview:_whiteView];
    
    UIImageView *searchImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 15, 15)];
    searchImageView.image = [UIImage imageNamed:@"mapSearch_image"];
    [_whiteView addSubview:searchImageView];
    
    _textField = [[UITextField alloc]init];
    _textField.placeholder = @"您现在在哪";
    _textField.borderStyle = UITextBorderStyleNone;
    _textField.clearButtonMode = UITextFieldViewModeAlways;
    _textField.delegate = self;
    [_textField addTarget:self action:@selector(textFieldAction:) forControlEvents:UIControlEventEditingChanged];
    [_whiteView addSubview:_textField];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchImageView.mas_right).offset(3);
        make.right.equalTo(_whiteView.mas_right).offset(-3);
        make.top.equalTo(_whiteView.mas_top);
        make.bottom.equalTo(_whiteView.mas_bottom);
    }];
}

#pragma mark --- 地图放大缩小
- (void)buttonAction:(UIButton *)button{
    if(button.tag == 1){
        _zoomLeve++;
        if(_zoomLeve == 20){
            _zoomLeve = 20;
        }
        [_mapView setZoomLevel:_zoomLeve];
    }else if (button.tag == 2){
        _zoomLeve--;
        if(_zoomLeve == 4){
            _zoomLeve = 4;
        }
        [_mapView setZoomLevel:_zoomLeve];
    }else if (button.tag == 3){
    //点击大头针获取地址
        CLog(@"确定");
        if(_pointArr.count){
            AMapPOI *poi = _pointArr[0];
            NSString *allStr =[NSString stringWithFormat:@"%@%@%@",poi.province,poi.city,poi.district];
            if(self.block){
                self.block(poi.location.latitude,poi.location.longitude,[NSString stringWithFormat:@"%@%@",poi.city,poi.district],poi.address,allStr);
            }
            NSArray *temArray = self.navigationController.viewControllers;
            
            for(UIViewController *temVC in temArray)
                
            {
                if ([temVC isKindOfClass:[QPerfectOrderInforMationVC class]])
                    
                {
                    [self.navigationController popToViewController:temVC animated:YES];
                }
                
            }
            
            
            NSDictionary *dict = @{@"province":poi.province, @"city":poi.city,@"district":poi.district,@"address":poi.address};
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gainAddressNotification" object:nil userInfo:dict];
        }
    }
}

#pragma mark --- 定位成功
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    [self.locationManager stopUpdatingLocation];
    [self locateTolatituWithcoor2D:location.coordinate];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
    [self.locationManager stopUpdatingLocation];
}

#pragma mark --- 移动到指定位置
- (void)locateTolatituWithcoor2D:(CLLocationCoordinate2D)coord{
    MACoordinateSpan span = MACoordinateSpanMake(0.05, 0.05);
    MACoordinateRegion region = MACoordinateRegionMake(coord, span);
    [_mapView setRegion:region animated:YES];
    _pointAnnotation.coordinate = coord;
    _pointAnnotation.title = @"目的地";
    NSArray *annotations = [NSArray arrayWithArray:_mapView.annotations];
    for (MAPointAnnotation *annotation in annotations) {
        if (![[annotation class] isMemberOfClass:[MAUserLocation class]]) {
            [_mapView removeAnnotation:annotation];
        }
    }
    [_mapView addAnnotation:_pointAnnotation];
    //周边搜索
    [self searchlatitude:coord.latitude longitude:coord.longitude];
}

#pragma mark ---- 周边搜索
- (void)searchlatitude:(double)latitude longitude:(double)longitude{
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:latitude longitude:longitude];
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    request.offset = 10;
    request.requireExtension = YES;
    [_search AMapPOIAroundSearch:request];
}

#pragma mark --- textfieleAction
- (void)textFieldAction:(UITextField *)textField {

    if(textField.text.length == 0){
        _tableView.hidden = YES;
    }
    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = textField.text;
    tipsRequest.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    [_search AMapInputTipsSearch: tipsRequest];
}

#pragma mark --- 实现POI搜索结果
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0){
        return;
    }
    [_pointArr removeAllObjects];
    for (AMapPOI *p in response.pois) {
        [_pointArr addObject:p];
    }
    if(_pointArr.count){
        AMapPOI *poi = _pointArr[0];
        _textField.text = poi.name;
    }
}

#pragma mark --- 实现textfiled搜索结果
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0){
        return;
    }
    [_dataArr removeAllObjects];
    for (AMapTip *p in response.tips) {
        [_dataArr addObject:p];
    }
    _tableView.hidden = NO;
    _maskView.hidden = NO;
    [_tableView reloadData];
}

#pragma mark --- 地图Delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if([annotation isMemberOfClass:[MAUserLocation class]]){
        return nil;
    }else{
    
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= NO;
        annotationView.hidden = YES;
        return annotationView;
    }
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{

    if(wasUserAction){
        CGPoint centerpoint = {kScreenWidth/2,(kScreenHeight-(kNavHeight+kStatusHeight))/2};
        CLLocationCoordinate2D coor2d = [self.mapView convertPoint:centerpoint toCoordinateFromView:self.mapView];
        _pointAnnotation.coordinate = coor2d;
        [_mapView addAnnotation:_pointAnnotation];
        [self searchlatitude:coor2d.latitude longitude:coor2d.longitude];
        
        CGAffineTransform transform = _centerBtn.transform;
        _centerBtn.transform = CGAffineTransformTranslate(transform, 0, -15);
        [UIView animateWithDuration:1.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
           _centerBtn.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
        }];
    }
}

//*********************************************//tableView********************************************
- (void)createTableView{

    __block QMapLocationVC *wSelf = self;

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.layer.borderWidth = 0.5;
    _tableView.layer.borderColor = [QColorUtility defaultLineColor].CGColor;
    _tableView.rowHeight = 60;
    _tableView.hidden = YES;
    _tableView.backgroundColor = [QColorUtility defaultBackGroundColor];
    [_maskView addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_whiteView.mas_bottom).offset(5);
        make.left.equalTo(_whiteView.mas_left).offset(0);
        make.right.equalTo(_whiteView.mas_right).offset(0);
        make.bottom.equalTo(wSelf.view.mas_bottom).offset(-10);
    }];
    [_tableView registerNib:[UINib nibWithNibName:@"QPlaceMapCell" bundle:nil] forCellReuseIdentifier:@"QPlaceMapCell"];
}

#pragma mark --- tableViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [_textField resignFirstResponder];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QPlaceMapCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QPlaceMapCell" forIndexPath:indexPath];
    cell.backgroundColor = [QColorUtility defaultBackGroundColor];
    if(_dataArr.count){
        cell.tip = _dataArr[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AMapTip *tip = _dataArr[indexPath.row];
    NSString *district = tip.district;
    if ([tip.address isEqualToString:@""]) {
        tip.address = tip.name;
    }
    NSString *allStr = [NSString stringWithFormat:@"%@%@",tip.district,tip.address];
    NSRange rang = [district rangeOfString:@"省"];
    NSLog(@"=======%@",district);

    if(rang.length != 0){
        district = [district substringFromIndex:rang.location+1];
    }
    if(self.block){
        self.block(tip.location.latitude,tip.location.longitude,district,tip.address,allStr);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
    /*NSString *address = [NSString stringWithFormat:@"%@%@",tip.district,tip.name];
    NSArray *temArray = self.navigationController.viewControllers;
    
    for(UIViewController *temVC in temArray)
        
    {
        
        if ([temVC isKindOfClass:[QPerfectOrderInforMationVC class]])
            
        {
            [self.navigationController popToViewController:temVC animated:YES];
            NSDictionary *dic = @{@"address":address};
            [[NSNotificationCenter defaultCenter]postNotificationName:@"NewAddressNotification" object:nil userInfo:dic];
            
        }
        
    }*/
}

@end
